<template>
  <div class="app-container page">
    <!-- 搜索条件表单 -->
    <div class="params-form app-container">
      <el-form :model="paramsForm" label-width="auto" ref="paramsRef">
        <el-form-item label="在售价">
          <div class="space">
            <el-input v-model="paramsForm.minPrice" />
            -
            <el-input v-model="paramsForm.maxPrice" />
          </div>
        </el-form-item>
        <el-form-item label="是否特价" prop="isSpecialPrice">
          <el-select v-model="paramsForm.isSpecialPrice">
            <el-option
              v-for="item in paramsOption.bool_type"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="商品风格" prop="productStyle">
          <el-select v-model="paramsForm.productStyle">
            <el-option
              v-for="item in paramsOption.shop_product_style"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否定制" prop="customType">
          <el-select v-model="paramsForm.customType">
            <el-option v-for="item in customTypeList" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否模型" prop="isModel">
          <el-select v-model="paramsForm.isModel">
            <el-option
              v-for="item in paramsOption.shop_is_model"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
            style="width: 100%"
            :options="paramsOption.classify"
            v-model="paramsForm.categoryId"
            :props="{ label: 'name', value: 'categoryId' }"
            :show-all-levels="false"
            clearable
            filterable
          />
        </el-form-item>
        <el-form-item label="线上同款" prop="isOnlineEquivalent">
          <el-select v-model="paramsForm.isOnlineEquivalent">
            <el-option label="有" :value="1"></el-option>
            <el-option label="无" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="form-btn">
        <el-button type="primary" :icon="Search" @click="init">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" plain @click="reset">重置</el-button>
      </div>
    </div>
    <!-- 操作tabs以及表头 -->
    <div class="sticky">
      <el-tabs v-model="paramsForm.productStatus" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane :label="'待审核(' + count.reviewedNum + ')'" :name="2"></el-tab-pane>
        <el-tab-pane :label="'审核驳回(' + count.downdNum + ')'" :name="6"></el-tab-pane>
        <el-tab-pane :label="'已上架(' + count.listingNum + ')'" :name="3"></el-tab-pane>
        <el-tab-pane :label="'即将下架(' + count.comingDownNum + ')'" :name="4"></el-tab-pane>
        <el-tab-pane :label="'已下架(' + count.delistNum + ')'" :name="5"></el-tab-pane>
        <el-tab-pane :label="'预发布(' + count.releaseNum + ')'" :name="1"></el-tab-pane>
        <el-tab-pane :label="'回收站(' + count.recycleNum + ')'" :name="7"></el-tab-pane>
        <el-tab-pane :label="'全部(' + count.allNum + ')'" :name="0"></el-tab-pane>
      </el-tabs>
      <div class="operate">
        <el-button type="primary" @click="inductsVisible = true">批量导入</el-button>
        <el-button type="primary" plain v-if="isShow('name')" @click="showModal('nameConfig')">批量修改商品名称 </el-button>
        <el-button type="primary" plain v-if="isShow('sales')" @click="showModal('virtualSalesConfig')">虚拟销量调整 </el-button>
        <el-button type="primary" plain v-if="isShow('model')" @click="showModal('modelConfig')">批量修改商品型号 </el-button>
        <el-button type="primary" plain v-if="isShow('move')" @click="openOperate('quash')">撤回商品</el-button>
        <el-button
          type="primary"
          v-if="isShow('publish')"
          @click="$router.push({ path: '/products/manage/add', query: { redirect: '/products/manage', tabs: '2' } })"
          >发布新品
        </el-button>
        <el-button type="primary" v-if="isShow('shelves')" @click="openBatch('up')">上架</el-button>
        <el-button text bg v-if="isShow('down')" @click="openBatch('down')">下架</el-button>
        <el-button text bg v-if="isShow('quashDown')" @click="openBatch('quashDown')">撤销下架</el-button>
        <el-button text bg v-if="isShow('reListed')" @click="openBatch('reListed')">重新上架</el-button>
        <el-button text bg v-if="isShow('del')" @click="openOperate('del')">删除</el-button>
        <el-input placeholder="请输入商品名称/品牌/商品分类关键词" v-model="paramsForm.search" @blur="init">
          <template #prefix>
            <el-icon class="el-input__icon">
              <search />
            </el-icon>
          </template>
        </el-input>
      </div>
      <div class="export-tips" v-if="exportNum > 0">有{{ exportNum }}个导入正在处理中，请稍后点击查询查看最新数据. . . .</div>
      <el-row class="table-head">
        <el-col :span="6">
          <div class="all">
            <el-checkbox @change="setCheckAll" v-model="checkAll" :indeterminate="isIndeterminate"></el-checkbox>
          </div>
          <span class="image-title">商品图</span>
          <span>商品信息</span>
        </el-col>
        <el-col :span="2"> 库存</el-col>
        <el-col :span="2" v-if="[4, 5].includes(paramsForm.productStatus)">
          <div>
            <span>占用库存</span>
            <el-tooltip
              class="box-item"
              effect="light"
              content="此商品存在已有采购商已加入签约合同，不久将发起采购单，此商品下架后，将不支持删除，避免影响已签约的合同采购单！"
              placement="bottom"
            >
              <el-button type="primary" link>
                <el-icon style="color: #909399">
                  <QuestionFilled />
                </el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </el-col>
        <el-col :span="[4, 5].includes(paramsForm.productStatus) ? 2 : 4"> 品牌</el-col>
        <el-col :span="2"> sku数</el-col>
        <el-col :span="2"> 价格</el-col>
        <el-col :span="2"> 上架日期</el-col>
        <el-col :span="2"> 实际销量</el-col>
        <el-col :span="2"> 状态</el-col>
        <el-col :span="2"> 操作</el-col>
      </el-row>
    </div>
    <!-- 列表 -->
    <div class="table-list">
      <el-empty description="空" v-if="!data.length" />
      <el-checkbox-group v-model="checkedList">
        <div class="goods" v-for="(goods, index) in data" :key="goods.collectId">
          <div class="business-name jzt-flex-bt">
            <div class="jzt-flex-center">
              <div class="all">
                <el-checkbox :value="goods.productId" @change="checked" />
              </div>
              <span style="cursor: default" @click="toPathPreview(goods)">{{ goods.productName }}</span>
            </div>
            <div class="recommend-wrap jzt-flex-center f12" v-if="goods.isRecommend">
              <img class="mr6" src="@/assets/images/recommend.png" alt="" /> 搭配推荐
            </div>
          </div>
          <el-row>
            <el-col :span="6">
              <img class="image" :src="goods.mainPicUrl || defaultImage" alt="" />
              <div class="info" style="white-space: break-spaces; word-break: break-all">
                <div>上架类目：{{ goods.preview }}</div>
                <div>型号：{{ goods.modeCode }}</div>
                <div>分类：{{ goods.categoryName }}</div>
                <div>ID：{{ goods.productId }}</div>
                <div v-if="paramsForm.type == 4" class="red">工厂对此件商品进行了下架，请提前安排</div>
              </div>
            </el-col>
            <el-col :span="2">
              {{ goods.factoryStock }}
            </el-col>
            <el-col :span="2" v-if="[4, 5].includes(paramsForm.productStatus)">
              <el-button type="primary" link @click="clickOpenOccupy(goods)">
                {{ goods?.waitOccupyNum }}
              </el-button>
            </el-col>
            <el-col
              :span="[4, 5].includes(paramsForm.productStatus) ? 2 : 4"
              style="white-space: break-spaces; word-break: break-all"
            >
              {{ goods.brandName }}
            </el-col>
            <el-col :span="2">
              <el-button type="primary" link size="small" @click="openSku">
                {{ goods.skuNum }}
              </el-button>
            </el-col>
            <el-col :span="2"><span v-if="goods.isSpecialPrice == 1">特价</span>￥{{ goods.factoryLowestPrice }}</el-col>
            <el-col :span="2">
              {{ goods.listingTime || "--" }}
            </el-col>
            <el-col :span="2">
              {{ goods.saleNum }}
            </el-col>
            <el-col :span="2">
              <Status :goods="goods" />
            </el-col>
            <el-col :span="2">
              <div class="table-operate">
                <el-button
                  type="primary"
                  link
                  size="small"
                  v-if="tableBtn('edit', goods) && goods.isWillDelist != 1"
                  @click="toPath('/products/manage/edit', goods.productId)"
                  >编辑
                </el-button>
                <el-button type="primary" link size="small" v-if="tableBtn('read', goods)" @click="openOperate('read')"
                  >知道了
                </el-button>
                <el-button type="primary" link size="small" v-if="tableBtn('log', goods)" @click="openLog(goods)"
                  >日志
                </el-button>
                <el-button
                  type="primary"
                  link
                  size="small"
                  v-if="tableBtn('copy', goods)"
                  @click="toPath('/products/manage/copy', goods.productId)"
                  >复制
                </el-button>
                <el-button
                  type="primary"
                  link
                  size="small"
                  v-if="tableBtn('down', goods) && goods.isWillDelist != 1"
                  @click="openBatch('down', goods)"
                  >下架
                </el-button>
                <el-button type="primary" link size="small" v-if="tableBtn('up', goods)" @click="openInfoDialog(goods)"
                  >上架
                </el-button>
                <el-button
                  type="primary"
                  link
                  size="small"
                  v-if="tableBtn('reapply', goods)"
                  @click="toPath('/products/manage/re-applay', goods.productId)"
                  >重新申请
                </el-button>
                <el-button type="primary" link size="small" v-if="tableBtn('quash', goods)" @click="openOperate('quash', goods)"
                  >撤回商品
                </el-button>
                <el-button
                  type="primary"
                  link
                  size="small"
                  v-if="tableBtn('reListed', goods)"
                  @click="openBatch('reListed', goods)"
                  >重新上架
                </el-button>
                <el-button type="primary" link size="small" v-if="tableBtn('del', goods)" @click="openOperate('del', goods)"
                  >删除
                </el-button>
                <el-button type="primary" link size="small" v-if="goods.isWillDelist == 1" @click="openBatch('quashDown', goods)"
                  >撤销下架
                </el-button>
                <!-- 查看预览 -->
                <el-button type="primary" link size="small" @click="toPathPreview(goods)">查看预览</el-button>
              </div>
            </el-col>
          </el-row>
          <div class="remark" v-if="goods.productStatus == 6">
            <div class="label">备注：</div>
            <div>
              {{ goods.newOverruleReason }}
            </div>
          </div>
        </div>
      </el-checkbox-group>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="paramsForm.page"
        v-model:page-size="paramsForm.size"
        :page-sizes="[10, 20, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @change="init"
      />
    </div>
    <!-- 批量操作弹窗 -->
    <el-dialog
      v-model="visible"
      width="500"
      modal-class="manage-dialog"
      align-center
      center
      @close="closeReset"
      :show-close="false"
    >
      <template #header>
        <CustomTitle :title="formConfigs[modalType].title" />
      </template>
      <el-form :model="form" ref="formRef" :label-position="formConfigs[modalType].align">
        <el-form-item
          v-for="item in formConfigs[modalType].list"
          :prop="item.field"
          :key="item.field"
          :label="item.label"
          :rules="item.rules"
        >
          <el-input v-if="item.type == 'input'" v-model="form[item.field]" :placeholder="item.placeholder">
            <template #suffix>
              <span class="tip">{{ form[item.field] ? form[item.field].length : 0 }}/32</span>
            </template>
          </el-input>
          <el-input v-if="item.type == 'selectInput'" v-model="form.modeCode">
            <template #prepend>
              <el-select v-model="form.type" placeholder="请选择" style="width: 200px">
                <el-option label="开头固定增加" :value="0" />
                <el-option label="结尾固定增加" :value="1" />
                <el-option label="自定义型号序列增加" :value="2" />
              </el-select>
            </template>
            <template #suffix>
              <span class="tip">{{ form[item.field] ? form[item.field].length : 0 }}/32</span>
            </template>
          </el-input>
          <el-space v-if="item.type == 'inputRange'">
            <el-input v-model="form[item.minField]" />
            -
            <el-input v-model="form[item.maxField]" />
          </el-space>
          <span class="tip">{{ item.tip }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="confirm"> 保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 日志弹窗 -->
    <el-dialog v-model="logVisible" modal-class="log-dialog" width="900" align-center center>
      <template #header>
        <div class="log-title">
          <CustomTitle title="商品操作日志" />
        </div>
      </template>
      <GoodsDetail :goodsList="goodsList" :default-image="defaultImage" />
      <div class="blank"></div>
      <div class="list">
        <div class="line" v-for="item in goodsList[0].list" :key="item.logId">
          {{ item.logDesc }}
          <div>
            操作人：{{ item.createBy }}<span>{{ item.createTime }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 操作二次确认提示 -->
    <el-dialog v-model="sureVisibel" width="400" align-center center :show-close="false">
      <div class="sure">
        <div>
          <el-icon>
            <Warning />
          </el-icon>
        </div>
        <span>{{ operate.type == "del" && paramsForm.productStatus == 7 ? "注意：一旦删除，将无法恢复！" : operate.title }}</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sureVisibel = false">取消</el-button>
          <el-button type="primary" @click="operateConfirm[operate.type]" v-if="!isSigning">
            {{ operate.type === "read" ? "我已知晓" : "确定" }}
          </el-button>
          <el-button v-else type="primary" @click="sureVisibel = false">我知道了</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 数据列表操作弹窗 -->
    <BatchModal v-model:batchVisible="batchVisible" :goodsList="goodsList" :batchType="batchType" :confirmBatch="confirmBatch">
      <template #list>
        <div class="batch-list">
          <GoodsDetail :goodsList="goodsList" :defaultImage="defaultImage" />
        </div>
      </template>
    </BatchModal>

    <!-- 占用库存明细弹窗 -->
    <el-dialog
      v-model="occupyOpen"
      width="1200"
      modal-class="manage-dialog"
      align-center
      center
      @close="occupyOpen = false"
      :show-close="true"
    >
      <template #header>
        <CustomTitle :title="'占用数量'" />
      </template>
      <OccupyTable :tableData="occupyData" />
    </el-dialog>
    <Inducts v-model:visible="inductsVisible" v-if="inductsVisible" @ok="handleInductsOk" />
    <!-- 上架 编辑sku弹窗 -->
    <infoDetail :btnLoading="_btnLoading" :optionInfo="optionInfo2" @submit="submitOk" @close="closeInfoDialog" />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { RefreshRight, Search, QuestionFilled } from "@element-plus/icons-vue";
import { nameConfig, sureConfig } from "./config";
import CustomTitle from "@/components/CustomTitle/index.vue";
import { selectDictDataByType } from "@/apis/dict/dict";
import {
  getCategoryTree,
  getLog,
  getFactoryList,
  editFactoryName,
  upFactory,
  downFactory,
  getFactoryCount,
  cancelSoldOut,
  deleteFactory,
  deleteRecycle,
  recoveryFactory,
  anewUp,
  lockPurchase,
  batchLockPurchase,
  getInProgressCount
} from "@/apis/manage";
import { ElMessage } from "element-plus";
import defaultImage from "@/assets/default.png";
import GoodsDetail from "./components/GoodsDetail.vue";
import Status from "@/components/Status/index.vue";
import router from "@/router";
import BatchModal from "./components/BatchModal.vue";
import { useRoute } from "vue-router";
import OccupyTable from "./components/occupyTable.vue";
import Inducts from "./components/Inducts.vue";

const customTypeList = [
  { dictValue: 1, dictLabel: "不可定制" },
  { dictValue: 2, dictLabel: "可定制" }
];
const route = useRoute();
const inductsVisible = ref(false);
const paramsRef = ref(null);
const checkAll = ref(false);
const isIndeterminate = ref(false);
const checkedList = ref([]);
const formRef = ref();
const form = ref({});
const modalType = ref("");
const visible = ref(false);
const logVisible = ref(false);
const sureVisibel = ref(false);
const paramsForm = ref({
  page: 1,
  size: 10,
  productStatus: 0,
  sourceType: 1
});
const operate = ref({
  title: "",
  desc: ""
});
const goodsList = ref([]);
const exportNum = ref(0);
const batchVisible = ref(false);
const batchType = ref("");
const paramsOption = ref({});
const visibleAlter = ref(false);
const total = ref(0);
const data = ref([]);
const count = ref({
  reviewedNum: 0,
  downdNum: 0,
  listingNum: 0,
  comingDownNum: 0,
  delistNum: 0,
  releaseNum: 0,
  recycleNum: 0,
  allNum: 0,
  priceChangeNum: 0,
  userNum: 0
});
const occupyOpen = ref(false); //占用库存明细弹窗
const occupyData = ref([]); //占用库存明细
const occupyDataBatch = ref([]); //占用库存明细-批量

//跳转预览页
const toPathPreview = row => {
  const routeUrl = router.resolve({
    path: "/products/manage/preview",
    query: { id: row?.tempLinkId || row?.productId }
  });
  window.open(routeUrl.href, "_blank");
};

// ===================================上架 编辑sku弹窗=================================================
import infoDetail from "./components/infoDetail/index.vue";
import { eidtProduct } from "@/apis/products/specifications";

const optionInfo2 = ref({ isShow: false });
const _btnLoading = ref(false);
const submitOk = editInfo => {
  console.log("这里请求立即上架接口", editInfo);
  _btnLoading.value = true;

  eidtProduct({ ...editInfo, publishStatus: 2 })
    .then(res => {
      if (res.code === 200) {
        _btnLoading.value = false; //弹窗“确认”按钮loading关闭
        optionInfo2.value.isShow = false; //弹窗关闭

        ElMessage.success("操作成功");
        init();
        getListCount();
      } else {
        _btnLoading.value = false; //弹窗“确认”按钮loading关闭
      }
    })
    .catch(err => {
      _btnLoading.value = false; //弹窗“确认”按钮loading关闭
    });
};

/**
 * 打开详情数据组件弹窗
 */
const openInfoDialog = data => {
  optionInfo2.value.isShow = true;
  optionInfo2.value.categoryId = data.categoryId;
  optionInfo2.value.collectId = data.collectId;
  optionInfo2.value.productId = data.productId;
  optionInfo2.value.data = data;
  optionInfo2.value.categoryList = paramsOption.value.classify;
};
/**
 * 关闭详情数据组件弹窗
 */
const closeInfoDialog = () => {
  optionInfo2.value.isShow = false;
};

// ===========================================================================================================

/**
 * 打开占用库存明细弹窗
 */
const clickOpenOccupy = obj => {
  occupyOpen.value = true;
  lockPurchase({ productId: obj.productId }).then(res => {
    if (res.code === 200) {
      occupyData.value = res.data || [];
    }
  });
};
/**
 * 批量商品查询占用库存列表
 */
const batchLockPurchaseFun = (prodIdArr = []) => {
  batchLockPurchase({ productIds: prodIdArr }).then(res => {
    if (res.code === 200) {
      occupyDataBatch.value = res.data || [];
      goodsList.value = occupyDataBatch.value;
      // goodsList.value = [{}];
    }
  });
};
/**
 * 路由跳转
 */
const toPath = (url, productId) => {
  router.push({
    path: url,
    query: {
      productId,
      redirect: "/products/manage",
      tabs: paramsForm.value.productStatus
    }
  });
};
/**
 * 地址栏是否带回了tabs参数
 */
const setRouteTabs = () => {
  if (route.query.tabs) {
    const tabs = route.query.tabs;
    paramsForm.value.productStatus = Number(tabs);
  }
};
/**
 * 切换tab标签的回调
 */
const handleClick = value => {
  data.value = [];
  checkAll.value = false;
  isIndeterminate.value = false;
  checkedList.value = [];
  init();
};
const formConfigs = { nameConfig };
/**
 * 表头上方按钮显示控制
 */
const isShow = btnType => {
  let operaterBtn = {
    name: [1, 3, 4, 5, 6, 7], //批量修改名字
    sales: false, // 批量修改销量
    model: false, // 批量修改型号
    import: true, // 批量导入
    move: [7], // 移入预发布
    publish: true, // 发布
    shelves: [1], // 上架
    down: [3], // 下架
    quashDown: [4], // 撤销下架
    del: [6, 5, 1, 7], //删除
    reListed: [5] //重新上架
  };
  if (paramsForm.value.productStatus === 0) return !!operaterBtn[btnType];
  return typeof operaterBtn[btnType] == "boolean"
    ? operaterBtn[btnType]
    : operaterBtn[btnType].includes(paramsForm.value.productStatus);
};
/**
 * 表格操作按钮控制
 */
const tableBtn = (btnType, goods) => {
  /**
   * userInfo.value.tenantTypeCode: 1:工厂 2:商家
   * operaterBtn key:按钮类型 value:是否显示 为数组:部分显示 数组值为 tabs页name值;
   */
  let operaterBtn = {
    edit: [3, 1, 9], // 编辑
    read: [8], // 知道了
    log: true, // 日志
    copy: [3, 5, 1, 9], // 复制
    down: [3, 9], // 下架
    reapply: [6], // 重新申请
    quash: [7], // 撤销
    reListed: [5], // 重新上架
    del: [5, 1, 6, 7], // 删除
    up: [1], // 上架
    refunded: [1], // 返还平台
    quashDown: [4]
  };
  return typeof operaterBtn[btnType] == "boolean" ? operaterBtn[btnType] : operaterBtn[btnType]?.includes(goods.productStatus);
};
/**
 * 重置搜索条件
 */
const reset = () => {
  paramsForm.value.maxPrice = undefined;
  paramsForm.value.minPrice = undefined;
  paramsRef.value.resetFields();
  init();
};
/**
 * 重置批量操作表单
 */
const closeReset = () => {
  formRef.value.resetFields();
};
/**
 * 打开批量操作弹窗
 */
const showModal = title => {
  if (checkedList.value == 0) return ElMessage.error("请选择商品");
  if (title == "modelConfig") {
    form.value.type = 0;
  } else {
    form.value = {};
  }
  visible.value = true;
  modalType.value = title;
};
const value = ref(Date.now() + 1000 * 60 * 60 * 7);
/**
 * 保存按钮的回调
 */
const confirm = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      const editParam = { ...form.value, productId: checkedList.value };
      const res = await editFactoryName(editParam);
      ElMessage.success("修改成功");
      init();
      if (res.code == 200) visible.value = false;
    }
  });
};

const operateConfirm = {
  close: res => {
    if (res.code == 200) {
      sureVisibel.value = false;
      init();
      getListCount();
      ElMessage.success("操作成功");
    }
  },
  del: async () => {
    const delList = goodsList.value.filter(v => v.productStatus != 7).map(v => v.productId);
    const recycleList = goodsList.value.filter(v => v.productStatus == 7).map(v => v.productId);
    console.log(delList, recycleList);
    if (delList.length) {
      const res = await deleteFactory({ productIds: delList });
      operateConfirm.close(res);
    }
    if (recycleList.length) {
      const res = await deleteRecycle({ productIds: recycleList });
      operateConfirm.close(res);
    }
  },
  quash: async () => {
    // 回收站恢复
    const res = await recoveryFactory({ productIds: goodsList.value.map(v => v.productId) });
    operateConfirm.close(res);
  },
  read() {
    console.log("知道了");
  }
};
/**
 * 打开批量操作弹窗
 */
const openBatch = (type, goods) => {
  batchType.value = type;
  if (goods || checkedList.value.length) {
    if (goods) {
      goodsList.value = [goods];
    } else {
      goodsList.value = data.value.filter(v => checkedList.value.includes(v.productId));
    }
    let isOpen = true;
    isOpen = goodsList.value.every(v => tableBtn(type, v) || v.isWillDelist == 1);
    console.log("批量下架", type);
    if (type === "down") {
      // 批量下架，查询所选商品的占用列表
      batchLockPurchaseFun(goodsList.value.map(item => item.productId));
    }
    if (!isOpen) {
      ElMessage.error("存在不可操作商品！");
    }
    if (isOpen) batchVisible.value = true;
  } else {
    return ElMessage.error("请选择商品");
  }
};
/**
 * 批量操作上/下架
 */
const confirmBatch = {
  close: res => {
    if (res.code == 200) batchVisible.value = false;
    init();
    getListCount();
    ElMessage.success("操作成功");
  },
  reListed: async () => {
    // 重新上架
    const res = await anewUp({ productIds: goodsList.value.map(v => v.productId) });
    confirmBatch.close(res);
  },
  up: async () => {
    // 上架
    const res = await upFactory({ productIds: goodsList.value.map(v => v.productId) });
    confirmBatch.close(res);
  },
  down: async form => {
    // 下架
    const res = await downFactory({ productIds: goodsList.value.map(v => v.productId), ...form });
    confirmBatch.close(res);
  },
  quashDown: async () => {
    // 撤销下架
    const res = await cancelSoldOut({ productIds: goodsList.value.map(v => v.productId) });
    confirmBatch.close(res);
  }
};
/**
 * 选中
 */
const checked = () => {
  checkAll.value = checkedList.value.length == data.value.length;
  isIndeterminate.value = checkedList.value.length != data.value.length && checkedList.value.length != 0;
};
/**
 * 设置全选
 */
const setCheckAll = () => {
  checkedList.value = checkAll.value ? data.value.map(item => item.productId) : [];
  isIndeterminate.value = false;
};
/**
 *  显示SKU弹窗
 */
const openSku = () => {
  // visibleSku.value = true;
};
/**
 * 查看日志
 */
const openLog = async goods => {
  const res = await getLog(goods.productId);
  goodsList.value = [{ list: res.data, ...goods }];
  logVisible.value = true;
};
/**
 * 打开变更明细弹窗
 */
const openAlter = () => {
  visibleAlter.value = true;
};
/**
 * 获取列表选项字典
 * @param {*} dictType 字典类型
 */
const getDict = async dictType => {
  const res = await selectDictDataByType(dictType);
  paramsOption.value[dictType] = res.data;
};
/**
 * 初始化列表
 */
const init = async () => {
  const categoryId = paramsForm.value.categoryId
    ? paramsForm.value.categoryId[paramsForm.value.categoryId.length - 1]
    : paramsForm.value.categoryId;
  const paramData = {
    ...paramsForm.value,
    productStatus:
      paramsForm.value.productStatus == 0 || paramsForm.value.productStatus == 9 || paramsForm.value.productStatus == 4
        ? ""
        : paramsForm.value.productStatus,
    categoryId,
    isWillDelist: paramsForm.value.productStatus == 4 ? 1 : null
  };
  const countKey = {
    2: "reviewedNum",
    6: "downdNum",
    3: "listingNum",
    4: "comingDownNum",
    5: "disabledNum",
    1: "releaseNum",
    7: "recycleNum",
    0: "allNum"
  };
  // 工厂
  const res = await getFactoryList(paramData);
  total.value = res.data.total;
  data.value = res.data.records;
  count.value[countKey[paramsForm.value.productStatus]] = res.data.total;
  await getInProgress();
};
const getListCount = async () => {
  const res = await getFactoryCount();
  count.value = res.data;
};
/**
 * 打开二次确认弹窗
 */
const isSigning = ref(true); //是否存在“在途签约合同”
const openOperate = (type, goods) => {
  operate.value = { type, title: sureConfig[type] };
  goodsList.value = goods ? [goods] : data.value.filter(v => checkedList.value.includes(v.productId));
  let isOpen = true;
  isOpen = goodsList.value.every(v => tableBtn(type, v));
  if (!goodsList.value.length) {
    ElMessage.error("请选择商品！");
  } else if (!isOpen) {
    ElMessage.error("存在不可操作商品！");
  } else {
    if (type === "del") {
      // 删除的时候，校验该商品是否存在“在途签约合同”。存在的商品禁止删除
      console.log("要删除的商品===", goods);
      if (goods?.waitOccupyNum > 0) {
        isSigning.value = true;
        operate.value.title = "当前商品存在，在途签约合同，系统不支持删除该商品，需要等在途合同商品完结后，才能删除！";
      } else {
        isSigning.value = false;
      }
      sureVisibel.value = true;
    } else {
      sureVisibel.value = true;
    }
  }
};
/**
 *  获取分类
 */
const getClassify = async () => {
  const res = await getCategoryTree();
  paramsOption.value.classify = res.data;
};
const handleInductsOk = () => {
  paramsForm.value.productStatus = 1;
  init();
};
const getInProgress = async () => {
  const { data } = await getInProgressCount();
  exportNum.value = data || 0;
};
onMounted(() => {
  // userInfo.value = window.microApp.getData().userInfo;
  setRouteTabs();
  getClassify();
  const dictArr = ["shop_product_custom_type", "shop_product_style", "bool_type", "shop_is_model", "shop_product_custom_type"];
  dictArr.forEach(item => {
    getDict(item);
  });
  init();
  getListCount();
});
</script>

<style lang="scss" scoped>
@import "index";
</style>
<style lang="scss">
.recommend-wrap {
  width: 90px;
  height: 24px;
  line-height: 24px;
  padding: 0 12px 0 4px;
  border-radius: 12px 0 0 12px;
  box-sizing: border-box;
  background-color: #ff8928;
  color: white;
  justify-content: flex-start !important;
}

.head-tip {
  width: 300px;
}

.manage-dialog {
  .el-input__wrapper {
    background: #f2f3f5;
  }
}

.log-dialog {
  padding: 0 !important;

  .el-dialog {
    padding: 24px 0 40px !important;
  }

  .goods-detail {
    padding: 0 20px;
  }
}
</style>
